<template>
  <scroll-view class="page-scroll" scroll-y="true">
    <view class="user" :style="{ backgroundImage: `url(${currentBackground})` }">
      <!-- 用户信息包裹容器 -->
      <view class="user-info">
        <!-- 头像 -->
        <view class="avatar-container">
          <image :src="avatar || defaultAvatar" class="avatar" mode="aspectFill"></image>
        </view>
        
        <!-- 用户名，可换行 -->
        <view class="username-container">
          <text class="username">{{ username || '未设置用户名' }}</text>
        </view>
      </view>
      
      <!-- 扫码按钮 -->
      <view class="scan" @click="scanQRCode">
        <image src="/static/mine/scan.png" mode="aspectFill"></image>
      </view>
    </view>
    
    <!-- 会员中心 -->
    <view class="member">
      <view class="title">
        <text>会员中心</text>
        <text>立享多重权益</text>
      </view>
      <view class="tab">
        <view class="item" v-for="item in memberItems" :key="item.text">
          <image v-if="item.icon" :src="item.icon" class="item-icon"></image>
          <text>{{ item.num }}</text>
          <text>{{ item.text }}</text>
        </view>
      </view>
    </view>
    
    <!-- 菜单 -->
    <view class="service-list">
      <view 
        class="service-item" 
        v-for="(item, index) in allServices" 
        :key="index"
        @click="handleServiceClick(item)"
      >
        <view class="left">
          <view class="service-icon" :class="item.class">
            <uni-icons :type="item.icon" size="20" color="#fff"></uni-icons>
          </view>
          <text class="service-name">{{ item.name }}</text>
        </view>
        <view class="right">
          <text v-if="item.desc" class="desc">{{ item.desc }}</text>
          <uni-icons type="right" size="14" color="#999"></uni-icons>
        </view>
      </view>
    </view>
    
    <!-- 主题切换弹窗 -->
    <view class="theme-modal" v-if="showThemeModal">
      <view class="modal-content">
        <view class="modal-header">
          <text class="modal-title">选择背景图片</text>
          <text class="close-btn" @click="closeThemeModal">×</text>
        </view>
        <view class="image-grid">
          <view 
            class="image-item" 
            v-for="(image, index) in backgroundImages" 
            :key="index"
            @click="selectBackgroundImage(image)"
          >
            <image :src="image" mode="aspectFill" class="thumbnail"></image>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 退出登录弹窗 -->
    <view class="logout-modal" v-if="showLogoutModal">
      <view class="modal-content">
        <view class="modal-header">
          <text class="modal-title">确认退出</text>
        </view>
        <view class="modal-body">
          <text>是否确认退出登录？</text>
        </view>
        <view class="modal-footer">
          <button class="cancel-btn" @click="showLogoutModal = false">取消</button>
          <button class="confirm-btn" @click="confirmLogout">确认</button>
        </view>
      </view>
    </view>
    
    <!-- 扫描结果弹窗 -->
    <view class="scan-modal" v-if="showScanModal">
      <view class="modal-content">
        <view class="modal-header">
          <text class="modal-title">扫描结果</text>
          <text class="close-btn" @click="showScanModal = false">×</text>
        </view>
        <view class="modal-body">
          <text>{{ scanResult }}</text>
        </view>
      </view>
    </view>
    
  </scroll-view>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { ApiGetUser } from "../../pages/api/user.js";
import { useAuthStore } from '../../store/token.js';
import { useInfoStore } from "../../store/user.js";

const user = useInfoStore();
const showThemeModal = ref(false);
const showLogoutModal = ref(false);
const showScanModal = ref(false);
const scanResult = ref('');
const currentBackground = ref('https://ts1.tc.mm.bing.net/th/id/R-C.59620170afedc7d6090190d5cf5abcdb?rik=P%2fuPsqBbZgd3wg&riu=http%3a%2f%2fn.sinaimg.cn%2fsinacn20110%2f569%2fw1920h1049%2f20190508%2fb663-hwsffza7768772.jpg&ehk=8%2fyKugFFySraMu0bPAwi%2bjmN7%2fsMJg6huhPbPqHZQj0%3d&risl=&pid=ImgRaw&r=0');
const userInfo = ref(null);
const defaultAvatar = ref('https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'); // 默认头像

// 获取用户信息
const getUsetInfos = async () => {
  try {
    const res = await ApiGetUser();
    userInfo.value = res;
    user.userInfo = res; // 更新缓存
    updateUserDisplay();
  } catch (error) {
    console.error("获取用户信息失败:", error);
    uni.showToast({
      title: "获取用户信息失败，请重试",
      icon: "none"
    });
  }
};


// 更新用户显示
const updateUserDisplay = () => {
  if (userInfo.value) {
    avatar.value = userInfo.value.avatar || defaultAvatar.value;
    username.value = userInfo.value.username || '未设置用户名';
  }
};

// 用户头像和名称
const avatar = ref(defaultAvatar.value);
const username = ref('未设置用户名');

onMounted(() => {
  if (!user.userInfo) {
    getUsetInfos();
  } else {
    userInfo.value = user.userInfo;
    updateUserDisplay();
  }
});

// 会员
const memberItems = ref([
  {
    num: '',
    text: '会员权利',
    icon: '/static/mine/crown-fill.png'
  },
  {
    num: '',
    text: '会员好礼',
    icon: '/static/mine/gift-fill.png'
  },
  { num: '3', text: '我的卡券' },
  { num: '12', text: '账户余额' }
]);

// 背景图片数组
const backgroundImages = ref([
  'https://cdn.acwing.com/media/article/image/2024/01/25/181746_655312d3bb-0125_1.jpg',
  'https://n.sinaimg.cn/sinacn20110/567/w1915h1052/20190508/fd26-hwsffza7768851.jpg',
  'https://img.keaitupian.cn/newupload/09/1631526070533748.jpg',
  'https://img-baofun.zhhainiao.com/fs/3fc54f2b553dc552c23fd2df0ee0159e.jpg',
  'https://ts1.tc.mm.bing.net/th/id/R-C.55545cd6eb6d7bbd1a467442f0d50e66?rik=mD5kUtHuPyeNKQ&riu=http%3a%2f%2fn.sinaimg.cn%2fsinacn20110%2f600%2fw1920h1080%2f20190508%2fc057-hwsffza7769015.jpg&ehk=bM12hqHX6tE5Xri6kFH1Lez67AhXyjq6jVBcJN8GUxY%3d&risl=&pid=ImgRaw&r=0',
  'https://tse1-mm.cn.bing.net/th/id/OIP-C.N4_UfpgbbE8lcul8o2nuvQHaEm?cb=iwp2&rs=1&pid=ImgDetMain',
  'https://n.sinaimg.cn/sinacn20110/580/w1920h1060/20190508/092f-hwsffza7769165.jpg',
  'https://cdn.acwing.com/media/article/image/2024/01/25/181746_a6f7a892bb-0125_13.jpg',
  'https://ts1.tc.mm.bing.net/th/id/R-C.59620170afedc7d6090190d5cf5abcdb?rik=P%2fuPsqBbZgd3wg&riu=http%3a%2f%2fn.sinaimg.cn%2fsinacn20110%2f569%2fw1920h1049%2f20190508%2fb663-hwsffza7768772.jpg&ehk=8%2fyKugFFySraMu0bPAwi%2bjmN7%2fsMJg6huhPbPqHZQj0%3d&risl=&pid=ImgRaw&r=0'
]);

// 选择背景图片
const selectBackgroundImage = (image) => {
  currentBackground.value = image;
  showThemeModal.value = false;
};

// 关闭主题切换弹窗
const closeThemeModal = () => {
  showThemeModal.value = false;
};

// 菜单
const allServices = ref([
  { name: '客服中心', icon: 'headphones', path: '/pages/mine/service', class: 'bg-orange', desc: '在线客服' },
  { name: '主题切换', icon: 'image', path: '', class: 'bg-green' },
  { name: '今日天气', icon: 'fire-filled', path: '/pages/mine/weather', class: 'bg-blue' },
  { name: '每日一签', icon: 'calendar', path: '/pages/mine/sign', class: 'bg-purple' },
  { name: '设置用户', icon: 'gear', path: '/pages/mine/setting', class: 'bg-cyan' },
  { name: '退出登录', icon: 'circle-filled', path: '', class: 'bg-gray' }
]);

// 处理菜单项点击
const handleServiceClick = (item) => {
  if (item.name === '主题切换') {
    showThemeModal.value = true;
  } else if (item.name === '扫一扫') {
    scanQRCode();
  } else if (item.name === '退出登录') {
    showLogoutModal.value = true;
  } else if (item.path && item.path !== '') {
    uni.navigateTo({ url: item.path });
  }
};

// 确认退出登录
const confirmLogout = () => {
  showLogoutModal.value = false;
  uni.navigateTo({ url: "/pages/login/login" });
  // 清除用户信息的逻辑
  user.userInfo = null;
  //清除token
  // 获取 Pinia store
  const authStore = useAuthStore();
  authStore.clearToken();
  uni.setStorageSync("hasVisited", "");
};

// 导航方法
const navigateTo = (path) => {
  if (path && path !== '') {
    uni.navigateTo({ url: path });
  }
};

// 扫描二维码
const scanQRCode = () => {
  uni.scanCode({
    success: (res) => {
      scanResult.value = res.result;
      showScanModal.value = true;
    },
    fail: (err) => {
      console.error('扫码失败:', err);
      uni.showToast({
        title: '扫码失败，请重试',
        icon: 'none'
      });
    },
    complete: () => {
      uni.hideLoading();
    }
  });
};
</script>

<style lang="scss">
/* 滚动视图容器 */
.page-scroll {
  height: 100vh; /* 占满整个视口高度 */
  background: #f0f0f0;
  
  /* 隐藏滚动条 - 适用于微信小程序等环境 */
  &::-webkit-scrollbar {
    display: none;
  }
  
  /* 兼容其他环境 */
  scrollbar-width: none;
  -ms-overflow-style: none;
}

/* 用户信息区域 */
.user {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 120px;
  width: 100%;
  padding: 25rpx;
  box-sizing: border-box;
  background-size: cover;
  background-position: center;
  position: relative;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.avatar-container {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  overflow: hidden;
  border: 2rpx solid rgba(255, 255, 255, 0.8);
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.avatar {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.username-container {
  max-width: 500rpx; /* 限制最大宽度 */
}

.username {
  font-size: 16px;
  font-weight: 500;
  color: #fff;
  text-shadow: 0 1rpx 2rpx rgba(0, 0, 0, 0.3);
  word-break: break-all;
  display: -webkit-box;
  -webkit-line-clamp: 2; /* 最多显示2行 */
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.scan {
  width: 60rpx;
  height: 60rpx;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.2);
  backdrop-filter: blur(4rpx);
  display: flex;
  align-items: center;
  justify-content: center;
  margin-left: 10rpx;
  
  image {
    width: 42rpx;
    height: 42rpx;
  }
  
  &:active {
    background: rgba(255, 255, 255, 0.4);
  }
}

/* 会员中心 */
.member {
  background: #182D4E;
  height: 230rpx;
  width: 700rpx;
  border-radius: 16rpx;
  margin: 10px auto 0;
  color: #D8B774;
  
  .title {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 15rpx 20rpx;
    
    text {
      font-weight: bold;
      
      &:nth-child(1) {
        font-size: 16px;
      }
      
      &:nth-child(2) {
        font-size: 12px;
        color: rgba(216, 183, 116, 0.8);
      }
    }
  }
  
  .tab {
    display: flex;
    justify-content: space-between;
    padding: 15rpx 20rpx;
    
    .item {
      width: 130rpx;
      height: 100rpx;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      border-radius: 10rpx;
      
      &:active {
        background: rgba(255, 255, 255, 0.05);
      }
      
      .item-icon {
        width: 40rpx;
        height: 40rpx;
        margin-bottom: 10rpx;
      }
      
      text {
        &:first-child {
          font-size: 16px;
          font-weight: bold;
        }
        
        &:last-child {
          margin-top: 5rpx;
          font-size: 12px;
          color: rgba(216, 183, 116, 0.8);
        }
      }
    }
  }
}

/* 菜单列表 */
.service-list {
  background: #fff;
  border-radius: 24rpx;
  margin: 10px 15rpx 0;
  padding: 10rpx 30rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.04);
  padding-bottom: 50px;

  .service-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 30rpx 0;
    border-bottom: 2rpx solid #f5f6fa;

    &:last-child {
      border-bottom: none;
    }

    .left {
      display: flex;
      align-items: center;

      .service-icon {
        width: 64rpx;
        height: 64rpx;
        border-radius: 32rpx;
        margin-right: 24rpx;
        display: flex;
        align-items: center;
        justify-content: center;
      }

      .service-name {
        font-size: 28rpx;
        color: #333;
      }
    }

    .right {
      display: flex;
      align-items: center;

      .desc {
        font-size: 24rpx;
        color: #999;
        margin-right: 16rpx;
      }
    }
  }
}

/* 颜色类 */
.bg-red { background: #ff4d4f; }
.bg-blue { background: #1890ff; }
.bg-green { background: #52c41a; }
.bg-purple { background: #722ed1; }
.bg-orange { background: #fa8c16; }
.bg-cyan { background: #13c2c2; }
.bg-pink { background: #eb2f96; }
.bg-gray { background: #666666; }

/* 弹窗 */
.theme-modal, .logout-modal, .scan-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;

  .modal-content {
    background: #fff;
    border-radius: 16rpx;
    width: 80%;
    max-height: 70%;
    overflow: hidden;
  }

  .modal-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20rpx 30rpx;
    border-bottom: 2rpx solid #f5f6fa;

    .modal-title {
      font-size: 32rpx;
      font-weight: 600;
    }

    .close-btn {
      font-size: 40rpx;
      font-weight: bold;
    }
  }

  .image-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 20rpx;
    padding: 30rpx;
    max-height: 60%;
    overflow-y: auto;

    .image-item {
      .thumbnail {
        width: 100%;
        height: 160rpx;
        border-radius: 16rpx;
      }
    }
  }
}

.logout-modal .modal-content {
  background: #fff;
  border-radius: 16rpx;
  width: 80%;
  padding: 30rpx;
}

.logout-modal .modal-body {
  text-align: center;
  padding: 20rpx 0;
}

.logout-modal .modal-footer {
  display: flex;
  justify-content: center;
  gap: 20rpx;
  padding-top: 20rpx;
  border-top: 2rpx solid #f5f6fa;
}

.logout-modal .cancel-btn, .logout-modal .confirm-btn {
  padding: 10rpx 40rpx;
  font-size: 28rpx;
  border: none;
  border-radius: 12rpx;
}

.logout-modal .cancel-btn {
  background: #f5f6fa;
  color: #333;
}

.logout-modal .confirm-btn {
  background: #ff4d4f;
  color: #fff;
}

.scan-modal .modal-content {
  background: #fff;
  border-radius: 16rpx;
  width: 80%;
  max-width: 500rpx;
  padding: 30rpx;
}

.scan-modal .modal-body {
  padding: 20rpx 0;
}

.scan-modal .modal-body text {
  word-break: break-all;
  font-size: 28rpx;
  color: #333;
}
</style>